package com.tledu.stu_manager.controller.student; /**
 *
 */

import com.alibaba.fastjson.JSONObject;
import com.tledu.stu_manager.constant.Constant;
import com.tledu.stu_manager.dao.StudentDao;
import com.tledu.stu_manager.exception.CustomException;
import com.tledu.stu_manager.model.Student;
import com.tledu.stu_manager.result.Result;
import com.tledu.stu_manager.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "StuListServlet", urlPatterns = "/stu/list")
public class StuListServlet extends HttpServlet {
    private StudentService studentService;

    @Override
    public void init() throws ServletException {
        super.init();
        studentService = new StudentService(new StudentDao());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            resp.setContentType(Constant.CONTENT_TYPE);
            PrintWriter out = resp.getWriter();
            if (req.getParameter("pageSize") == null) {
                req.getRequestDispatcher("/WEB-INF/student/student-list.jsp").forward(req, resp);
                return;
            }
            Integer pageSize = Integer.parseInt(req.getParameter("pageSize"));
            Integer pageNum = Integer.parseInt(req.getParameter("pageNum"));
            List<Student> list = studentService.findList(pageNum, pageSize);
            out.print(JSONObject.toJSONString(new Result(200, true, "查询成功", list)));

        } catch (CustomException e) {
            e.printStackTrace();
            req.setAttribute("msg", e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }
}
